import { defineComponent } from 'vue';
import { addarticle, getarticle, delarticle, searcharticle } from '@/api/article';
import { updatearticle } from '@/api/article';
import { dayjs, ElMessageBox, ElMessage } from 'element-plus';
import type { Action } from 'element-plus';
import { ref, reactive } from 'vue';
import axios from 'axios';
import ImageUploader from 'quill-image-uploader';

export default defineComponent({
    data() {
        return {
            value: '',
            input: '',
            radio: ref(2),
            dialogFormVisible: false,
            stateform: false,
            // 弹窗隐藏初始化
            // 初始化数据字段数据
            article: {
                title: '',
                introduction: '',
                picture: '',
                Associatestore: '',
                sort: '',
                contet: '',
                state: '',
            },
            editarticle: {
                title: '',
                introduction: '',
                picture: '',
                Associatestore: '',
                sort: '',
                contet: '',
                state: '',
            },
            // 存储数据
            list: [],
            fileList: [],
            limit: 10,
            page: 1,
            total: 1,
            // 编辑弹窗初始化
            showEdit: false,
            rules: {
                title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
              },
            modules: {
                name: 'imageUploader',
                module: ImageUploader,
                options: {
                  upload(file: any) {
                    console.log('file', file);
                    return new Promise((resolve) => {
                      const formdata = new FormData();
                      formdata.append('file', file);
                      formdata.append('type', 'qf2302');
                      axios
                        .post('http://www.wzsqyg.com/attachment/upload', formdata)
                        .then((reulst: any) => {
                          console.log('reulst', reulst);
                          resolve(reulst.data.msg);
                        });
                    });
                  },
                },
              },
        };
    },
    mounted() {
        this.getList();
    },
    methods: {
        // 编辑店铺弹窗
        openEdit(row: any) {
            this.editarticle = row;
            this.showEdit = true;
        },
        // 删除店铺
        handleDel(id: number) {
            // 删除的操作一般需要二次确认 避免用户误操作
            ElMessageBox.alert('是否确认删除该数据项？', '系统提示', {
                confirmButtonText: '确认',
                callback: async (action: Action) => {
                    if (action === 'cancel') return false;
                    const res = await delarticle(id);
                    console.log('真正的去执行删除', res);
                    if (res.status === 200) {
                        this.$message.success('删除成功');
                        this.getList();
                    } else {
                        this.$message.warning('删除失败');
                    }
                    return true;
                },
            });
        },
        // 编辑店铺
        async handleEidt() {
            console.log('editarticle', this.editarticle);
            const { id, ...postdata } = this.editarticle;
            const res = await updatearticle(id, postdata);
            console.log('res', res);
            const { status } = res;
            if (status === 200) {
                this.$message.success('修改成功');
                this.showEdit = false;
                this.getList();
            } else {
                this.$message.warning('修改失败');
            }
        },
        handeSizeChange(val: number) {
            console.log('val', val);
            this.limit = val;
            this.getList();
        },
        handlePageChange(val: number) {
            this.page = val;
            this.getList();
        },
       // 获取数据
       async getList() {
        const data = {
          $limit: this.limit,
          $skip: (this.page - 1) * this.limit,
        };
        if (this.input.trim() !== '') {
          (data as any).title = this.input;
        }
        if (this.value !== '') {
          (data as any).state = this.value;
        }
        const res = await getarticle(data);
        this.list = res.data.data;
        console.log(this.list);
        this.total = res.data.total;
      },
      //刷新数据
      async getListRest() {
        this.input = '';
        this.value = '';
        this.getList();
      },
        //转换时间
        formatTime(time: string) {
            return dayjs(time).format('YYYY-MM-DD HH:MM:ss');
        },
        //   增加店铺
        async articleAdd(article) {
            console.log('article', this.article);
            const res = await addarticle(this.article);
            console.log('res', res);
            const { status } = res;
            console.log('status', status);
            if (status === 201) {
                this.$message.success('添加成功');
                this.dialogFormVisible = false;
                this.getList(); // 添加成功之后重新的获取列表内容
            } else {
                this.$message.warning('添加失败');
            }
        },
        // 上传图片
        handleUpload(options: any) {
            // 实际工作当中我们更多的是自己去执行上传的具体操作 因为上传前我们还有可以需要进行压缩操作等
            //  打印查看里面的属性
            console.log('options', options);
            // options.file就是我们要上传的文件对象
            // FormData 表格类型阿贾克斯上传文件 先new 一个表格类型
            const formdata = new FormData();
            // 在调用一个方法 formdata.append 添加
            formdata.append('file', options.file); // 实践当中对于这个file对象一般还需要进行压缩处理等
            formdata.append('type', 'qf2302');
            // 引入接口上传
            // 返回一个promise对像
            return axios.post('http://www.wzsqyg.com/attachment/upload', formdata);
        },
        // 上传前的约束 自动上传
        // rawFilez 组件带的 ：类型 boolean组件要求要返回return
        beforeAvatarUpload(rawFile: any): boolean {
            // 获取的是组件中的属性值
            // 可以获取大小，名称，类型
            console.log('rawFile', rawFile);
            // 使用上传之前的钩子我们可以对于上传的文件进行检测或者大小的判断 方法点属性
            // includes 意为包含 image 图片
            // 上传类型不是图片就停止上传
            if (!rawFile.type.includes('image')) {
                this.$message.warning('只能上传图片文件');
                return false;
            }
            // 大小要转换一下 最初为bit
            //  兆 kb bit
            const min = 0.001 * 1024 * 1024;
            if (rawFile.size < min) {
                // warning 警告
                this.$message.warning('上传的图片不能小于0.2m');
                //  若返回false或者返回 Promise 且被 reject，则停止上传 组件是规定
                return false;
            }
            return true;
        },
        // respons 回调一个地址
        UploadOk(response: any) {
            console.log('response', response);
            // 将返回的值 等于商品表里面的封面
            this.article.picture = response.msg;
        },
        //修改状态
        changestate(row: any, val: number, id: number) {
            if (!val) {
                console.log('启动');
                ElMessageBox.confirm(
                    `确定启用"${row.title}"吗？`,
                    '系统提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    },
                )
                    .then(async () => {
                        console.log('点击了确认');
                        this.editDengji = row;
                        let { ...postdata } = this.editDengji;
                        postdata.state = 1;
                        await updatearticle(id, postdata);
                        this.getList();
                        ElMessage({
                            type: 'success',
                            message: '启用成功',
                        });
                    }).catch(async () => {
                        this.editDengji = row;
                        let { ...postdata } = this.editDengji;
                        postdata.state = 0;
                        await updatearticle(id, postdata);
                        this.getList();
                    });
            } else {
                console.log('关闭');
                ElMessageBox.confirm(
                    `确定禁用"${row.title}"吗？`,
                    '系统提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    },
                )
                    .then(async () => {
                        this.editDengji = row;
                        let { ...postdata } = this.editDengji;
                        postdata.state = 0;
                        await updatearticle(id, postdata);
                        this.getList();
                        ElMessage({
                            type: 'success',
                            message: '禁用成功',
                        });
                    }).catch(async () => {
                        this.editDengji = row;
                        let { ...postdata } = this.editDengji;
                        postdata.state = 1;
                        await updatearticle(id, postdata);
                        this.getList();
                    });
            }
        },
    },
});
